// pages/message/message.js
import { messageListData } from '../../utils/mockData.js';

Page({
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      });
    }
  },

  /**
   * 页面的初始数据
   */
  data: {
    messageList: messageListData,
    startX: 0,
    startY: 0,
    currentIndex: -1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 消息点击事件
   */
  onMessageClick(e) {
    const index = e.currentTarget.dataset.index;
    const contactName = e.currentTarget.dataset.name;
    const message = this.data.messageList[index];
    
    // 如果当前消息的删除按钮是打开的，则关闭它
    if (message.swipeOpen) {
      this.closeAllSwipes();
      return;
    }
    
    // 验证数据
    if (!message || !contactName) {
      wx.showToast({
        title: '数据错误',
        icon: 'none'
      });
      return;
    }
    
    // 清除未读消息
    if (message.unread > 0) {
      const messageList = this.data.messageList;
      messageList[index].unread = 0;
      this.setData({ messageList });
    }
    
    // 跳转到对话页面
    wx.navigateTo({
      url: `/pages/message/message-dialog/message-dialog?contactName=${encodeURIComponent(contactName)}`,
      success: () => {
        // 跳转成功
      },
      fail: (err) => {
        console.error('跳转失败:', err);
        wx.showToast({
          title: '跳转失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 触摸开始事件
   */
  onTouchStart(e) {
    const index = e.currentTarget.dataset.index;
    const touch = e.touches[0];
    
    // 关闭其他已打开的消息
    this.closeOtherSwipes(index);
    
    this.setData({
      startX: touch.clientX,
      startY: touch.clientY,
      currentIndex: index
    });
  },

  /**
   * 触摸移动事件
   */
  onTouchMove(e) {
    const index = e.currentTarget.dataset.index;
    const touch = e.touches[0];
    const deltaX = touch.clientX - this.data.startX;
    const deltaY = touch.clientY - this.data.startY;
    
    // 如果垂直滑动距离大于水平滑动距离，则不处理
    if (Math.abs(deltaY) > Math.abs(deltaX)) {
      return;
    }
    
    const messageList = this.data.messageList;
    
    // 处理向左滑动（显示删除按钮）
    if (deltaX < 0) {
      const swipeDistance = Math.min(Math.abs(deltaX), 120);
      
      // 实时更新滑动距离
      messageList[index].swipeDistance = swipeDistance;
      messageList[index].swipeOpen = swipeDistance > 60;
      this.setData({ messageList });
    }
    // 处理向右滑动（隐藏删除按钮）
    else if (deltaX > 0 && messageList[index].swipeOpen) {
      const swipeDistance = Math.max(0, 120 - deltaX);
      
      // 实时更新滑动距离
      messageList[index].swipeDistance = swipeDistance;
      messageList[index].swipeOpen = swipeDistance > 60;
      this.setData({ messageList });
    }
    // 处理向右滑动（当删除按钮未打开时，确保消息卡片回到初始位置）
    else if (deltaX > 0) {
      // 确保消息卡片完全回到初始位置
      messageList[index].swipeDistance = 0;
      messageList[index].swipeOpen = false;
      this.setData({ messageList });
    }
  },

  /**
   * 触摸结束事件
   */
  onTouchEnd(e) {
    const index = e.currentTarget.dataset.index;
    const touch = e.changedTouches[0];
    const deltaX = touch.clientX - this.data.startX;
    
    const messageList = this.data.messageList;
    
    // 处理向左滑动（显示删除按钮）
    if (deltaX < 0) {
      if (Math.abs(deltaX) > 60) {
        messageList[index].swipeOpen = true;
        messageList[index].swipeDistance = 120;
      } else {
        messageList[index].swipeOpen = false;
        messageList[index].swipeDistance = 0;
      }
    }
    // 处理向右滑动（隐藏删除按钮）
    else if (deltaX > 0) {
      if (messageList[index].swipeOpen) {
        if (deltaX > 60) {
          messageList[index].swipeOpen = false;
          messageList[index].swipeDistance = 0;
        } else {
          messageList[index].swipeOpen = true;
          messageList[index].swipeDistance = 120;
        }
      } else {
        // 确保消息卡片完全回到初始位置
        messageList[index].swipeOpen = false;
        messageList[index].swipeDistance = 0;
      }
    }
    
    this.setData({ messageList });
  },

  /**
   * 关闭其他已打开的消息
   */
  closeOtherSwipes(currentIndex) {
    const messageList = this.data.messageList;
    messageList.forEach((item, index) => {
      if (index !== currentIndex && item.swipeOpen) {
        item.swipeOpen = false;
        item.swipeDistance = 0;
      }
    });
    this.setData({ messageList });
  },

  /**
   * 关闭所有滑动状态
   */
  closeAllSwipes() {
    const messageList = this.data.messageList;
    messageList.forEach(item => {
      item.swipeOpen = false;
      item.swipeDistance = 0;
    });
    this.setData({ messageList });
  },
  /**
   * 消息长按事件
   */
  onMessageLongPress(e) {
    const index = e.currentTarget.dataset.index;
    const message = this.data.messageList[index];
    
    wx.showActionSheet({
      itemList: ['标记为已读', '置顶对话', '删除对话'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            this.markAsRead(index);
            break;
          case 1:
            this.pinConversation(index);
            break;
          case 2:
            this.onDeleteMessage({ currentTarget: { dataset: { index } } });
            break;
        }
      }
    });
  },

  /**
   * 标记为已读
   */
  markAsRead(index) {
    const messageList = this.data.messageList;
    messageList[index].unread = 0;
    this.setData({ messageList });
    
    wx.showToast({
      title: '已标记为已读',
      icon: 'success'
    });
  },

  /**
   * 置顶对话
   */
  pinConversation(index) {
    const messageList = this.data.messageList;
    const message = messageList[index];
    
    // 移除原位置
    messageList.splice(index, 1);
    // 添加到顶部
    messageList.unshift(message);
    
    this.setData({ messageList });
    
    wx.showToast({
      title: '已置顶',
      icon: 'success'
    });
  },
  onDeleteMessage(e) {
    const index = e.currentTarget.dataset.index;
    const message = this.data.messageList[index];
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除与"${message.author.name}"的对话吗？`,
      confirmText: '删除',
      confirmColor: '#ff4757',
      success: (res) => {
        if (res.confirm) {
          const messageList = this.data.messageList;
          messageList.splice(index, 1);
          this.setData({ messageList });
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        } else {
          // 取消删除时关闭滑动状态
          this.closeAllSwipes();
        }
      }
    });
  }
})